package com.allin.mall.common.redis.serializer;

import com.google.gson.Gson;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

public class GsonRedisSerializer<T> implements RedisSerializer<T> {

    private static final byte[] EMPTY_ARRAY = new byte[0];

    private final Class<T> type;

    private final Gson gson;

    private final Charset charset;

    public GsonRedisSerializer(Charset charset, Gson gson, Class<T> type) {
        this.gson = gson;
        this.type = type;
        this.charset = charset;
    }

    @Override
    public byte[] serialize(T value) throws SerializationException {
        if (value == null) {
            return EMPTY_ARRAY;
        }
        return this.gson.toJson(value).getBytes(this.charset);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        return this.gson.fromJson(new String(bytes, this.charset), this.type);
    }
}
